package com.shop.shoporder.wapController;

import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.shop.shoporder.common.*;
import com.shop.shoporder.entity.*;
import com.shop.shoporder.service.*;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@RequestMapping("/wap")
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
public class QRCodeController {

    @Autowired
    EWMConfig ewmConfig;
    @Autowired
    GoodsService goodsService;
    @Autowired
    WapGoodsDetailsService wapGoodsDetailsService;
    @Autowired
    UploadFileConfig uploadFileConfig;

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ShortUrlService shortUrlService;
    @Autowired
    GroupbuyGoodService groupbuyGoodService;
    @Autowired
    GroupbuyService groupbuyService;

    Logger logger = LoggerFactory.getLogger(BannerController.class);

    //    @UserLoginToken
    @ResponseBody
    @RequestMapping("/getEnCode")
    public Response getEnCode(HttpServletRequest request) {
        String type = request.getParameter("type");//type:1首页，2产品，3为店铺,4为团购
        String text1 = request.getParameter("text");
        logger.info("转码前：------------------------------------>" + text1);
        String text = null;
        int strLong = 0;
        String paramURL = null;
        String decodeURL = null;
        String subURL = null;
        double groupbuyPrice = 0.0;
        int drawSign = 0;
        try {
            decodeURL = URLDecoder.decode(text1, "UTF-8");
            logger.info("转码后：------------------------------------>" + decodeURL);
            strLong = decodeURL.indexOf("/Share");
            if (strLong != -1) {
                subURL = decodeURL.substring(strLong);

//                paramURL = ShortURLUtil.getShortURL(subURL);//短链接

                String uuid = UUID.randomUUID().toString();
                paramURL = uuid.replaceAll("-", "");

                logger.info("---------------截取短链接------------->");

                LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
                if (lettuceConnectionFactory != null) {
                    lettuceConnectionFactory.setDatabase(1);//切换到缓存数据库1
                    redisTemplate.setConnectionFactory(lettuceConnectionFactory);
                    lettuceConnectionFactory.resetConnection();
                }

                redisTemplate.opsForValue().set(paramURL, subURL);
                //保存
                ShortUrl shortUrl = new ShortUrl();
                shortUrl.setShortKey(paramURL);
                shortUrl.setShortUrl(subURL);
                int row = shortUrlService.insertSelective(shortUrl);

            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        text = HttpRequestConfig.orderServerUrl + "/wap/shortURL?shortUrl=" + paramURL;
        System.out.println("text：" + text);


        int goodId = 0;
        int specId = 0;
        int x = 0;//二维码x坐标
        int y = 0;//二维码y坐标
        String fontSizeType = null;
        double price = 0.00;
        int groupbuyTotalCount = 0;
        //logo图片
        String logoImgURL = ewmConfig.getLogoImgPath();

        //二维码背景图图片
        String imgURL = null;

        //商品图片路径
        String guigeImgUrl = "http://xlspic.ycsqd.com/1552626038488.png";
        String productName = "传奇天露酒";
        String nameDesc = null;
        switch (type) {
            case "1":
                x = ewmConfig.getEwm_indexImg_x();
                y = ewmConfig.getEwm_indexImg_y();
                imgURL = ewmConfig.getIndexBgImg();
                QRCodeUtil.QRCODE_SIZE = 300;
                QRCodeUtil.HEIGHT = 60;
                QRCodeUtil.WIDTH = 60;
                break;
            case "2":
                QRCodeUtil.QRCODE_SIZE = 200;
                QRCodeUtil.HEIGHT = 30;
                QRCodeUtil.WIDTH = 30;
                x = ewmConfig.getEwm_img_x();
                y = ewmConfig.getEwm_img_y();
                String goodIds = request.getParameter("goodId");
                String specIds = request.getParameter("specId");
                if (goodIds != null || specIds != null || !StringUtil.isNumeric(goodIds) || !StringUtil.isNumeric(specIds)) {
                    goodId = Integer.parseInt(goodIds);
                    specId = Integer.parseInt(specIds);
                } else {
                    return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
                }
                //查询
                Map<String, String> map = new HashMap<>();
                map.put("Id", goodIds);
                map.put("specId", specIds);
                WapGoodsSpec wapGoodsSpec = null;
                try {
                    wapGoodsSpec = wapGoodsDetailsService.selectGoodsDetailsByGoodId(map);
                    if (wapGoodsSpec != null) {

                        //生产图片的路径
                        int n = wapGoodsSpec.getPiclist().indexOf(",");
                        if (n == -1) {
                            guigeImgUrl = wapGoodsSpec.getPiclist();
                        } else {
                            guigeImgUrl = wapGoodsSpec.getPiclist().substring(0, wapGoodsSpec.getPiclist().indexOf(","));
                        }

                        productName = wapGoodsSpec.getName();
                        nameDesc = wapGoodsSpec.getNameDesc();//宣传文字
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                imgURL = ewmConfig.getBgImgURL();
                break;
            case "3":
                QRCodeUtil.QRCODE_SIZE = 300;
                QRCodeUtil.HEIGHT = 60;
                QRCodeUtil.WIDTH = 60;
                x = ewmConfig.getEwm_storeImg_x();
                y = ewmConfig.getEwm_storeImg_y();
                imgURL = ewmConfig.getStoreBgImg();
                break;

            case "4":
                QRCodeUtil.QRCODE_SIZE = 200;
                QRCodeUtil.HEIGHT = 30;
                QRCodeUtil.WIDTH = 30;
                x = ewmConfig.getEwm_groupbuyImg_x();
                y = ewmConfig.getEwm_groupbuyImg_y();
                //查询商品图片
                int groupbuygoodId = 0;
                int gId = 0;
                int sId = 0;

                String groupbuygoodIds = null;
                GroupbuyGood groupbuyGood = null;
                groupbuygoodIds = request.getParameter("groupbuygoodId");
                if (groupbuygoodIds != null && !"".equals(groupbuygoodIds) && StringUtil.isNumeric(groupbuygoodIds)) {
                    groupbuygoodId = Integer.parseInt(groupbuygoodIds);
                }
                groupbuyGood = groupbuyGoodService.getGroupbuyGood(groupbuygoodId);
                System.out.println("---->" + groupbuyGood.getGoodsId());
                if (groupbuyGood != null) {
                    //产品ID和规格ID
                    gId = groupbuyGood.getGoodsId();
                    sId = groupbuyGood.getSpecId();
                    groupbuyPrice = groupbuyGood.getGroupbyPrice();
                }

                if (gId != 0 && sId != 0) {
                    //查询
                    Map<String, String> groupbuyMap = new HashMap<>();
                    groupbuyMap.put("Id", gId + "");
                    groupbuyMap.put("specId", sId + "");

                    WapGoodsSpec groupbuyWapGoodsSpec = null;
                    try {
                        groupbuyWapGoodsSpec = wapGoodsDetailsService.selectGoodsDetailsByGoodId(groupbuyMap);
                        if (groupbuyWapGoodsSpec != null) {

                            //生产图片的路径
                            int n = groupbuyWapGoodsSpec.getPiclist().indexOf(",");
                            if (n == -1) {
                                guigeImgUrl = groupbuyWapGoodsSpec.getPiclist();
                            } else {
                                guigeImgUrl = groupbuyWapGoodsSpec.getPiclist().substring(0, groupbuyWapGoodsSpec.getPiclist().indexOf(","));
                            }

                            productName = groupbuyWapGoodsSpec.getName();
                            nameDesc = groupbuyWapGoodsSpec.getNameDesc();//宣传文字
                            price = groupbuyWapGoodsSpec.getSpace().get(0).getPrice();
                            logger.info("---产品的名称-->" + productName + "----" + nameDesc);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }

                //团购的参与总人数
                int groupbuyId = 0;

                String groupbuyIds = request.getParameter("groupbuyId");
                if (groupbuyIds != null && !"".equals(groupbuyIds) && StringUtil.isNumeric(groupbuyIds)) {
                    groupbuyId = Integer.parseInt(groupbuyIds);
                }
                List<GroupbuyInfo> groupbuyInfoList = null;
                if (groupbuyId != 0) {
                    groupbuyInfoList = groupbuyService.getGroupbuyAndParticpaterInfo(groupbuyId);
                    groupbuyTotalCount = groupbuyInfoList.size()+groupbuyInfoList.get(0).getParticipaters().size();
                }
                imgURL = ewmConfig.getGroupbuyBgImg();
                break;

            default:
                imgURL = ewmConfig.getIndexBgImg();
                break;
        }

        //获取路径
        try {

            String ewm_pic1 = "1";
            String ewm_pic2 = "2";
            String ewm_pic3 = "3";
            String ewm_pic4 = "4";
            String ewm_pic5 = "5";
            String ewm_pic6 = "6";
            String ewm_pic7 = "7";
            String ewm_pic8 = "8";

            //服务器
            File path = new File(ewmConfig.getServerPath());
//            File path = new File(ewmConfig.getLocalPath());//本地
            if (!path.exists()) {
                path = new File("");
            }

            String logoUrl = path + logoImgURL;
            String erWMImgUrl = path + "";

            //生成二维码
            if ("2".equalsIgnoreCase(type)) {
                logoUrl = null;
            }

            erWMImgUrl += "/xxx/";

            System.out.println("路径：" + erWMImgUrl);

            erWMImgUrl = QRCodeUtil.encode(text, logoUrl, erWMImgUrl, true);//二维码路径

            ewm_pic1 = erWMImgUrl;

            String bgImg = path + imgURL;//背景图路径

            String uuId = UUID.randomUUID().toString().replace("-", "").substring(5, 10);

            //合成图片--背景图片和二维码合成
            String bg_code_img = MergeImage.mergeImage(bgImg, erWMImgUrl, x, y, ewmConfig.getLocalPath() + "xxx/");

            ewm_pic2 = bg_code_img;

            String str = null;
            String tarOutImg = null;

            if ("2".equalsIgnoreCase(type)) {//分享商品图片
                str = guigeImgUrl;

                URL url = new URL(str);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("GET");

                conn.setConnectTimeout(5 * 1000);

                InputStream inStream = conn.getInputStream();

                byte[] data = readInputStream(inStream);
                String outPath = path + "/xxx/" + uuId + str.substring(str.lastIndexOf("."));
                File imageFile = new File(outPath);

                FileOutputStream outStream = new FileOutputStream(imageFile);

                outStream.write(data);

                String fontType = "微软雅黑";
                String pro_bg_img = MergeImage.mergeImage(bg_code_img, outPath, ewmConfig.getPro_x(), ewmConfig.getPro_y(), ewmConfig.getLocalPath() + "xxx/");//商品图和带有二维码的图片合成
                String tarImg = path + "/xxx/" + "ewmbg-" + uuId + ".png";//绝对路径
                if (productName.length() > 8) {
                    productName = productName.substring(0, 10);
                }

                ewm_pic3 = pro_bg_img;

                ewm_pic6 = outPath;

                outStream.close();

                System.out.println("tarImg:" + tarImg);

                fontSizeType = "1";
                AddWaterMark.createMark(pro_bg_img, tarImg, productName, null, 1, fontType, 28, 610, 180, Color.BLACK, fontSizeType, drawSign);
                //宣传文字
                if (nameDesc.length() > 30) {
                    nameDesc = nameDesc.substring(0, 30);

                }

                ewm_pic4 = tarImg;

                fontSizeType = "0";
                tarOutImg = path + "/xxx/" + "ewmbg-" + uuId + "--00" + ".png";//绝对路径

                System.out.println("tarOutImg:" + tarOutImg);

                AddWaterMark.createMark(tarImg, tarOutImg, nameDesc, null, 1, fontType, 24, 610, 130, Color.BLACK, fontSizeType, drawSign);
                bgImg = tarOutImg;

                ewm_pic5 = tarOutImg;

            } else if ("4".equals(type)) {
                //团购分享图
                str = guigeImgUrl;

                URL url = new URL(str);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("GET");

                conn.setConnectTimeout(5 * 1000);

                InputStream inStream = conn.getInputStream();

                byte[] data = readInputStream(inStream);
                String outPath = path + "/xxx/" + uuId + str.substring(str.lastIndexOf("."));
                File imageFile = new File(outPath);

                FileOutputStream outStream = new FileOutputStream(imageFile);

                outStream.write(data);

                String fontType = "微软雅黑";
                String pro_bg_img = MergeImage.mergeImage(bg_code_img, outPath, ewmConfig.getGroupbuy_x(), ewmConfig.getGroupbuy_y(), ewmConfig.getLocalPath() + "xxx/");//商品图和带有二维码的图片合成
                String tarImg = path + "/xxx/" + "ewmbg-" + uuId + ".png";//绝对路径
                if (productName.length() > 8) {
                    productName = productName.substring(0, 10);
                }

                ewm_pic3 = pro_bg_img;

                ewm_pic6 = outPath;

                outStream.close();

                System.out.println("tarImg:" + tarImg + "--文字--->" + productName);

                fontSizeType = "1";
                AddWaterMark.createMark(pro_bg_img, tarImg, productName, null, 1, fontType, 32, 610, 180, Color.WHITE, fontSizeType, drawSign);
                //宣传文字
                if (nameDesc.length() > 30) {
                    nameDesc = nameDesc.substring(0, 30);

                }

                ewm_pic4 = tarImg;

                fontSizeType = "0";
                tarOutImg = path + "/xxx/" + "ewmbg-" + uuId + "--00" + ".png";//绝对路径

                System.out.println("tarOutImg:" + tarOutImg);

                String strPrice = "商城价:" + price + "元";
                String priceOutImg = path + "/xxx/" + "ewmbg-" + uuId + "--01" + ".png";//绝对路径
                drawSign = 1;
                //商城价
                AddWaterMark.createMark(tarImg, priceOutImg, strPrice, null, 1, fontType, 26, 610, 80, Color.WHITE, fontSizeType, drawSign);
                ewm_pic7 = priceOutImg;
                //人数
                String groupbuyCountOutImg = path + "/xxx/" + "ewmbg-" + uuId + "--02" + ".png";//绝对路径
                drawSign = 0;
                String strCount ="正在进行拼团，已有"+ groupbuyTotalCount + "人";
                AddWaterMark.createMark(priceOutImg, groupbuyCountOutImg, strCount, null, 1, fontType, 48, 560, 920, Color.WHITE, fontSizeType, drawSign);
                ewm_pic8 = groupbuyCountOutImg;

                drawSign = 0;
                nameDesc = "拼团价：" + groupbuyPrice;
                AddWaterMark.createMark(groupbuyCountOutImg, tarOutImg, nameDesc, null, 1, fontType, 36, 610, 130, Color.WHITE, fontSizeType, drawSign);
                bgImg = tarOutImg;

                ewm_pic5 = tarOutImg;

            }


            //上传
            String fileName = "erwm-" + new Random().nextInt(99999999) + ".png";//生成随机文件名;
            if (!"2".equalsIgnoreCase(type) && !"4".equals(type)) {
                tarOutImg = bg_code_img;
            }
            File file = new File(tarOutImg);
            FileInputStream fileInputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(fileName, file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

            fileInputStream.close();

            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone2());

            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //...生成上传凭证，然后准备上传


            //获取流
//            byte[] uploadBytes = multipartFile.getBytes();
            byte[] uploadBytes = multipartFile.getBytes();

            //默认不指定key的情况下，以文件内容的hash值作为文件名

            String key = fileName;

            Auth auth = Auth.create(uploadFileConfig.getAccessKey(), uploadFileConfig.getSecretKey());
            String upToken = auth.uploadToken(uploadFileConfig.getBucket());

            com.qiniu.http.Response response = uploadManager.put(uploadBytes, key, upToken);

            String filePath = uploadFileConfig.getDomainName() + "/" + fileName;

            //删除文件
            File file1 = new File(ewm_pic1);
            file1.delete();

            File file2 = new File(ewm_pic2);
            file2.delete();

            File file3 = new File(ewm_pic3);
            file3.delete();

            File file4 = new File(ewm_pic4);
            file4.delete();

            File file5 = new File(ewm_pic5);
            file5.delete();

            File file6 = new File(ewm_pic6);
            file6.delete();//

            File file7 = new File(ewm_pic7);
            file7.delete();//

            File file8 = new File(ewm_pic8);
            file8.delete();


            return new Response(MessageConstants.MSG_SUCCESS, filePath, 0, "", request);
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
        }

    }

    public String addWaterMark(String srcImgPath, String tarImgPath, String waterMarkContent, Color markContentColor, Font font, int x, int y) {
        try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);//得到文件
            Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高

            System.out.println("图片：" + srcImgWidth + "--" + srcImgHeight);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            g.setColor(markContentColor); //根据图片的背景设置水印颜色
            g.setFont(font); //设置字体

            //设置水印的坐标
//             x = srcImgWidth - 2 * getWatermarkLength(waterMarkContent, g);
//            System.out.println("--x-->"+getWatermarkLength(waterMarkContent, g));
//
//             y = srcImgHeight - 2 * getWatermarkLength(waterMarkContent, g);
//            System.out.println("--y-->"+getWatermarkLength(waterMarkContent, g));

            g.drawString(waterMarkContent, x, y);  //画出水印
            g.dispose();
            String uuId = UUID.randomUUID().toString().replace("-", "").substring(10, 15);
            String filename = "erwmc-" + uuId + ".png";

//            String localImgPath = "/Users/admin/Documents/ewm_img/";//本地
            String localImgPath = ewmConfig.getServerPath();
            File file = new File(localImgPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            tarImgPath = localImgPath + filename;
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
            ImageIO.write(bufImg, "png", new File(tarImgPath));
            System.out.println("添加水印完成");
            outImgStream.flush();
            outImgStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return tarImgPath;
    }

    public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }


    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
//        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


}
